package cn.momoky.ccool.service;

import cn.momoky.ccool.exception.GlobalException;
import cn.momoky.ccool.mapper.FileNodeMapper;
import cn.momoky.ccool.mapper.UserMapper;
import cn.momoky.ccool.pojo.FileNode;
import cn.momoky.ccool.pojo.User;
import cn.momoky.ccool.utils.UUID;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@AllArgsConstructor
public class UserService {

    private final UUID uuid;

    private final UserMapper userMapper;
    private final FileNodeMapper fileNodeMapper;

    public User add(User user) {

        User u = this.findByNameOrEmail(user.getName(), user.getEmail());
        if (u != null) {
            throw new GlobalException("用户已存在");
        }
        userMapper.add(user);

        FileNode fileNode = new FileNode();
        fileNode.setId(uuid.get())
                .setName(user.getName())
                .setPath("/" + user.getName())
                .setIsDir(true)
                .setCreateTime(System.currentTimeMillis())
                .setLastModified(fileNode.getCreateTime())
                .setLeft(1)
                .setRight(2);
        fileNodeMapper.add(fileNode);

        return user;
    }

    public User findByNameOrEmail(String name, String email) {
        return userMapper.findByNameOrEmail(name, email);
    }
}
